#include "Arduino.h"
#include "TemperatureHumidityDewpoint.h"
#include "dht.h"



TemperatureHumidityDewpoint::TemperatureHumidityDewpoint(int sensorPin,  double humidityCorrection) {
  _sensorPin = sensorPin;
  _humidityCorrection = humidityCorrection;
}


void TemperatureHumidityDewpoint::readSensor() {
  
  int chk = _dht.read22(_sensorPin);
  status = "Rreading";
  switch (chk) {
     case DHTLIB_OK:
        status = "OK";
        break;
    case DHTLIB_ERROR_CHECKSUM:
        status = "Checksum error";    
        break;
    case DHTLIB_ERROR_TIMEOUT:
        status = "Time out error";    
        break;
    default:
        status = "Unknown error";    
        break;
  }
  

  temperature = _dht.temperature;
  humidity = _dht.humidity;
  
  
  // adfruit
  /*
  DHT dht(_sensorPin, DHT22);
  temperature = dht.readTemperature();
  humidity = dht.readHumidity();  
  status = "OK";
  
 if (isnan(temperature) || isnan(humidity)) {
  status = "FAILURE"; 
 }
 */
 humidity = humidity + _humidityCorrection;

  _calculateDewpoint(temperature, humidity);
}


// delta max = 0.6544 wrt dewPoint()
// 6.9 x faster than dewPoint()
// reference: http://en.wikipedia.org/wiki/Dew_point
void TemperatureHumidityDewpoint::_calculateDewpoint(double celsius, double humidity) {
  double a = 17.271;
  double b = 237.7;
  double temp = (a * celsius) / (b + celsius) + log(humidity*0.01);
  double Td = (b * temp) / (a - temp);
  dewpoint = Td;
}









